var prod;
var total = 0;

$(document).ready(function(){
	$('#txtVlpago').blur(function(){
		var val = parseFloat($(this).val().replace('.','').replace(',','.'));
		$('#troco').html('Troco ' + formatDecimal((val - (total + ($('#txtVlentrega').val() == '' ? 0 : parseFloat($('#txtVlentrega').val())))).toFixed(2)));
	});
	
	$('#txtVlentrega').blur(function(){
		var val = parseFloat($('#txtVlpago').val().replace('.','').replace(',','.'));
		$('#troco').html('Troco ' + formatDecimal((val - (total + ($('#txtVlentrega').val() == '' ? 0 : parseFloat($('#txtVlentrega').val())))).toFixed(2)));
	});
	
	var val = parseFloat($('#txtVlpago').val().replace('.','').replace(',','.'));
	$('#troco').html('Troco ' + formatDecimal((val - (total + ($('#txtVlentrega').val() == '' ? 0 : parseFloat($('#txtVlentrega').val())))).toFixed(2)));
});

function openSelectProduto(){
	openSelect(1);
}

function openSelectPrato(){
	openSelect(2);
}
function openSelect(type){
  $.get('produto_list.jsp?type=' + type, function(data){
    $('body').append(data);
    prod = $('#produtos');
    prod.css('display', 'none');
    var w = prod.dialog({height: 340, modal: true});
  }, 'html');
}

function closeSelectProduto(){
  prod.dialog('destroy');
  prod.remove();
}

function addProduto(){
  $('#tblProdutos input:checked').each(function(i){
    var t = $(this);
    var itens = $('#tblPedido input[type="checkbox"]').toArray();
    for(var i in itens) {
      var inn = $(itens[i]);
      if(inn.attr('tt') == 'prod' &&inn.attr('id') == t.attr('id')) {
    	  return;
      }
    }
    
    addProd(t.attr('id'),t.attr('prod'),t.attr('valor'), 1);
  });
  closeSelectProduto();
  updateValor();
}

function addProd(id, nome, valor, qtd){
	$('#tblPedido > tbody:last').append('<tr><td> <input id="' + id + '" name="prod" type="checkbox" tt="prod" value="' + id + '" valor="' + valor + '"/> </td><td>' + nome + '</td> <td><input id="txt' + id + '" type="number" value="' + qtd + '" class="txt_qtd" onchange="updateValor();"/></td> <td>' + formatDecimal(valor) + '</td></tr>');
}

function removeProduto(){
  $('#tblPedido input:checked').each(function(i){
    $(this.parentNode.parentNode).remove();
  });
  updateValor();
}

function savePedido(b,e){
	if($('#txtCli').val() == ''){
		var foo = getDialog();
		foo.html('Você deve escolher um cliente.');
		foo.append(closeButton());
		foo.dialog({modal: true});
		return;
	}
	var vdata = 'txtCod=' + $('#txtCod').val() + '&txtCli=' + $('#txtCli').attr('clid');
	$('#tblPedido input[type=checkbox]').each(function(i){
	    vdata += '&prod=' + $(this).attr('id');
	});
	
	$('#tblPedido input[type=number]').each(function(i){
	    vdata += '&qtd=' + $(this).val();
	});
	
	if(b) vdata += '&fechado=true';
	if(e) vdata += '&entregue=true';
	vdata += '&endereco=' + $('#txtEndereco').val() + '&vlpago=' + $('#txtVlpago').val() + '&observacao=' + $('#txtObs').val() + '&vlentrega=' + $('#txtVlentrega').val();
	console.debug(vdata);
	$.ajax({
		url: 'rest/crud/pedido',
		data: vdata,
		type: 'POST',
		success: function(e){
			var foo = getDialog();
			foo.html('');
			foo.append('Salvo com sucesso.');
			foo.append(closeButton());
			foo.dialog({modal: true});
			window.location = 'ped.jsp?id=' + e;
		},
		error: function(e){
			var foo = getDialog();
			foo.html('');
			foo.append(e);
			foo.append(closeButton());
			foo.dialog({modal: true});
		}
	});
}

function openCliente(){
	$.get('cli_list.jsp', function(data){
	    $('body').append(data);
	    prod = $('#clientes');
	    prod.css('display', 'none');
	    var w = prod.dialog({height: 340, modal: true});
	  }, 'html');
}

function addCliente(){
	$('#container input:checked').each(function(){
	    var t = $(this);
	    clid = $('#txtCli').attr('clid');
	    if(clid == t.attr('id')) return;
	    $('#txtCli').attr('clid', t.attr('id'));
	    $('#txtCli').val(t.attr('valor'));
	    $('#txtCod').val('');
	    $('#txtEndereco').val(t.attr('endereco'));
	});
	closeSelectProduto();
}

function formatDecimal(num){
	num = num.toString().replace(',','.');
    num = num.toString().replace(/\$|\,|%/g,'');
    if(isNaN(num))
        num = "0";
    
    sign = (num == (num = Math.abs(num)));
    num = Math.floor(num*100+0.50000000001);
    cents = num%100;
    num = Math.floor(num/100).toString();
    if(cents<10)
        cents = "0" + cents;
    for (var i = 0; i < Math.floor((num.length-(1+i))/3); i++)
        num = num.substring(0,num.length-(4*i+3)) + '.' + num.substring(num.length-(4*i+3));

    return (((sign)?'':'-') + num + ',' + cents);
}

function addClienteS(id){
	var t = $('#container #'+id);
	clid = $('#txtCli').attr('clid');
    if(clid == t.attr('id')) {
    	closeSelectProduto();
    	return;
    }
    $('#txtCli').attr('clid', t.attr('id'));
    $('#txtCli').val(t.attr('valor'));
    $('#txtCod').val('');
    $('#txtEndereco').val(t.attr('endereco'));
    closeSelectProduto();
}

/*Prato
var prato;
function openSelectPrato(){
  $.get('prato_list.html', function(data){
    $('body').append(data);
    prato = $('#pratos');
    prato.css('display', 'none');
    var w = prato.dialog({height: 340, modal: true});
  }, 'html');
}

function closeSelectPrato(){
  prato.dialog('destroy');
  prato.remove();
}

function addPrato(){
  $('#tblPratos input:checked').each(function(i){
    var t = $(this);
    var itens = $('#tblPedido input[type="checkbox"]').toArray();
    for(var i in itens) {
      var inn = $(itens[i]);
      if(inn.attr('tt') == 'prato' && inn.attr('id') == t.attr('id')) {
	return;
      }
    }
    
    $('#tblPedido > tbody:last').append('<tr><td> <input id="' + t.attr('id') + '" type="checkbox" value="" tt="prato" valor="' + t.attr('valor') + '"/> </td><td>' + t.attr('prod') + '</td> <td><input id="txt' + t.attr('id') + '" type="number" value="1" class="txt_qtd" onchange="updateValor();"/></td> <td>' + t.attr('valor') + '</td></tr>');
  });
  closeSelectPrato();
  updateValor();
}*/

function updateValor(){
  total = 0;
  $('#tblPedido input[type="checkbox"]').each(function(i){
    total += parseInt(this.parentNode.parentNode.children[2].children[0].value) * parseFloat($(this).attr('valor'));
  });
  $('#valor').html(formatDecimal(total.toFixed(2)));
  var t = $('#txtVlpago');
  if(t.val()){
	  var val = parseFloat(t.val().replace('.','').replace(',','.'));
	  $('#troco').html('Troco ' + formatDecimal((val - (total - ($('#txtVlentrega').val() == '' ? 0 : parseFloat($('#txtVlentrega').val())))).toFixed(2)));
  }
  t.html('Troco 0.00');
}